package com.fish.anne.webapp.action;

import com.opensymphony.xwork2.Preparable;
import com.fish.anne.service.SystemArticleCatManager;
import com.fish.anne.model.SystemArticleCat;
import com.fish.anne.webapp.action.BaseAction;

import java.util.List;

public class SystemArticleCatAction extends BaseAction implements Preparable {
    private SystemArticleCatManager systemArticleCatManager;
    private List systemArticleCats;
    private SystemArticleCat systemArticleCat;
    private Long  catId;

    public void setSystemArticleCatManager(SystemArticleCatManager systemArticleCatManager) {
        this.systemArticleCatManager = systemArticleCatManager;
    }

    public List getSystemArticleCats() {
        return systemArticleCats;
    }

    /**
     * Grab the entity from the database before populating with request parameters
     */
    public void prepare() {
        if (getRequest().getMethod().equalsIgnoreCase("post")) {
            // prevent failures on new
            String systemArticleCatId = getRequest().getParameter("systemArticleCat.catId");
            if (systemArticleCatId != null && !systemArticleCatId.equals("")) {
                systemArticleCat = systemArticleCatManager.get(new Long(systemArticleCatId));
            }
        }
    }

    public String list() {
        systemArticleCats = systemArticleCatManager.getAll();
        return SUCCESS;
    }

    public void setCatId(Long  catId) {
        this. catId =  catId;
    }

    public SystemArticleCat getSystemArticleCat() {
        return systemArticleCat;
    }

    public void setSystemArticleCat(SystemArticleCat systemArticleCat) {
        this.systemArticleCat = systemArticleCat;
    }

    public String delete() {
        systemArticleCatManager.remove(systemArticleCat.getCatId());
        saveMessage(getText("systemArticleCat.deleted"));

        return SUCCESS;
    }

    public String edit() {
        if (catId != null) {
            systemArticleCat = systemArticleCatManager.get(catId);
        } else {
            systemArticleCat = new SystemArticleCat();
        }

        return SUCCESS;
    }

    public String save() throws Exception {
        if (cancel != null) {
            return "cancel";
        }

        if (delete != null) {
            return delete();
        }

        boolean isNew = (systemArticleCat.getCatId() == null);

        systemArticleCatManager.save(systemArticleCat);

        String key = (isNew) ? "systemArticleCat.added" : "systemArticleCat.updated";
        saveMessage(getText(key));

        if (!isNew) {
            return INPUT;
        } else {
            return SUCCESS;
        }
    }
}